#include"Heap.h"

void HPInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}
void HPDestroy(HP* php)
{
	assert(php->a);
	free(php->a);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}

void HPPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->a[php->capacity] = php->a[php->size])
	{
		HPDataType newcapacity = php->capacity == 0 ? 4 : 2 * sizeof(php->capacity);
		HPDataType *temp = (HPDataType*)realloc(php->a, maxsize * sizeof(php->capacity));
		if (temp == NULL)
		{
			perror("realloc fail");
		}

		php->a = temp;
		php->capacity = newcapacity;
	}  
	php->a[php->size - 1] = x;
	php->size++;
	AdjustUp( php-> a, php->size-1);

}
void AdjustUp(HPDataType* a, int child)
{
	HPDataType parent = (child - 1) / 2;
	while (child > 0)
	{

		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (parent - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void Swap(HPDataType* px, HPDataType* py)
{
	HPDataType* temp;
	temp = px;
	px = py;
	py = temp;
}

void HPPop(HP* php)
{
	assert(php);
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;
	int parent = 0;
	AdjustDown(php->a, php->size, parent);
}

void AdjustDown(HPDataType* a, int n, int parent)
{
	int child = 2 * parent + 1;
	while (child<n)
	{
		if (a[child]>a[child + 1])
		{
			child++;
		}
		if (a[parent] > a[child])
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = 2 * parent + 1;
		}
		else
		{
			break;
		}
	}
}
